<template>
  <div class="login-account">
    <el-form label-width="60px" :model="account" :rules="rules" ref="formRef">
      <el-form-item label="账号:" prop="name">
        <el-input v-model="account.name"></el-input>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="account.password"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ElForm } from 'element-plus'
import { defineComponent, reactive, ref } from 'vue'
import { rules } from '../config/account-config'
import dataCache from '@/utils/cache'
import { useStore } from 'vuex'

const account = reactive({
  name: dataCache.getCache('name') ?? '',
  password: dataCache.getCache('password') ?? ''
})
const formRef = ref<InstanceType<typeof ElForm>>()

const store = useStore()

const loginAction = (isKeepPassword: boolean) => {
  formRef.value?.validate((valid) => {
    if (valid) {
      // 1.判断是否需要记住密码
      if (isKeepPassword === true) {
        // 2.1.把账号信息存储在缓存中
        dataCache.setCache('name', account.name)
        dataCache.setCache('password', account.password)
      } else {
        // 2.2.把账号信息消除
        dataCache.deleteCache('name', account.name)
        dataCache.deleteCache('password', account.password)
      }
      // 2.发送action登录请求
      store.dispatch('login/accountLoginAction', { ...account })
    }
  })
}

defineExpose({
  loginAction
})
</script>

<style scoped></style>
